package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDrawPrizeItem;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 安徽福彩网 开奖结果抓取
 * 抓取安徽25选5  <br/>
 * 历史地址:  http://www.ahfc.gov.cn/dlp/cp_255.shtml<br/>
 * @author 
 *
 */
public class LotteryDrawFetch505WorkerOfficial extends AbstractLotteryDrawFetchWorker{

	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	protected static final String RESULT_HISTORY_LOCALITY_URL = "http://www.ahfc.gov.cn/dlp/cp_255.shtml";
	
	protected String siteName = "安徽福彩网";
	protected String lotteryScope = "安徽25选5";
	
	public LotteryDrawFetch505WorkerOfficial(){
		super(LotteryType.A_AH25);
	}
	@Override
	public LotteryDraw fetchResult(String phase) {
		return null;
	}
	
	private String fetchData(){
		String url = RESULT_HISTORY_LOCALITY_URL;
		String data = null;
		String pageInfo = "彩期为null时获取结果页面" + url;
		String encoding = "GBK";
		String logHeader = "==" + lotteryScope + "==" + siteName + "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";
		try {
			data = CoreFetcherUtils.URLGet(url, null, encoding);
		} catch (Exception e) {
			logger.error("获取html数据失败" + e.getMessage());
			return null;
		}
		
		if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}
		return data;
	}
	
	private String fetchLatestLotteryPhase(Parser parser) {
		String phase = "";
		NodeFilter filter = new TagNameFilter("table");
		NodeList nodeList = null;
		try {
			nodeList = parser.extractAllNodesThatMatch(filter);
			String tempStr ="";
			for (int i = 0; i < nodeList.size(); i++) {
				TableTag tempTable = (TableTag)nodeList.elementAt(i);
				tempStr = tempTable.getAttribute("style");
				if (StringUtils.contains(tempStr, "word-break:break-all")) {
					TableRow[] tableRows = tempTable.getRows();
					TableRow tableRow = tableRows[2];
					TableColumn column = tableRow.getColumns()[0];
					phase = column.toPlainTextString().trim();
					if (phase.length() == 5 && Integer.valueOf(phase) > 0) {
						return phase;
					} else {
						return null;
					}
				}
			}
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		
		return phase;
	}

	@Override
	public LotteryDraw fetchResultDetail(String phase) {
		
		String data = fetchData();
		Parser parser = null;
		String encoding = "GBK";
		try {
			parser = Parser.createParser(data,  encoding);
		} catch (Exception e) {
			logger.error("解析html页面失败" + e.getMessage());
			return null;
		}
		
		if (phase == null || "".equals(phase)) {
			phase = fetchLatestLotteryPhase(parser);
			if (StringUtils.isEmpty(phase)) {
				return null;
			}
		} else {
			try {
				String latestPhase = fetchLatestLotteryPhase(parser);
				if (Integer.valueOf(latestPhase).intValue() - Integer.valueOf(phase).intValue() >= 50) {
					logger.error("只能查询最近50期的安徽25选5数据");
					return null;
				}
			} catch (Exception e) {
				logger.error("安徽25选5彩期错误，原因：", e.getMessage());
				return null;
			}
		}
		
		try {
			parser.setInputHTML(data);
		} catch (Exception e) {
			logger.error("安徽25选5重新设置parser时错误，原因：", e.getMessage());
			return null;
		}
		
		LotteryDraw lotteryDraw = new LotteryDraw();
		NodeFilter filter = new TagNameFilter("table");
		NodeList nodeList = null;
		try {
			nodeList = parser.extractAllNodesThatMatch(filter);
			String tempStr ="";
			String strResult = "";
			for (int i = 0; i < nodeList.size(); i++) {
				TableTag tempTable = (TableTag)nodeList.elementAt(i);
				tempStr = tempTable.getAttribute("style");
				if (StringUtils.contains(tempStr, "word-break:break-all")) {
					TableRow[] tableRows = tempTable.getRows();
					for (TableRow tableRow : tableRows) {
						TableColumn column = tableRow.getColumns()[0];
						String tempPhase = column.toPlainTextString().trim();
						List<LotteryDrawPrizeItem> resultDetail = new ArrayList<LotteryDrawPrizeItem>();
						if (tempPhase.equals(phase)) {
							lotteryDraw.setPhase(phase);
							lotteryDraw.setLotteryType(this.getLotteryType());
							TableColumn drawTimeColumn = tableRow.getColumns()[1];
							lotteryDraw.setTimeDraw(CoreDateUtils.formatDate(CoreDateUtils.parseDate(drawTimeColumn.toPlainTextString().trim(), CoreDateUtils.DATE)));
							
							//中奖号码
							TableColumn drawNumColumn = tableRow.getColumns()[2];
							String tempNum = drawNumColumn.toPlainTextString().trim();
							String[] numArray = StringUtils.split(tempNum, " ");
							if (numArray.length ==5) {
								for (int m=0; m<numArray.length; m++) {
									if (m > 0) {
										strResult += ",";
									}
									strResult += numArray[m];
								}
								lotteryDraw.setResult(strResult);
							}
							TableColumn salesColumn = tableRow.getColumns()[3];
							lotteryDraw.setVolumeOfSales(salesColumn.toPlainTextString().trim());
							TableColumn jackpotColumn = tableRow.getColumns()[4];
							lotteryDraw.setJackpot(jackpotColumn.toPlainTextString().trim());
							
							//中奖明细
							TableColumn firstNumColumn = tableRow.getColumns()[5];
							TableColumn firstAmountColumn = tableRow.getColumns()[6];
							LotteryDrawPrizeItem firstItem = new LotteryDrawPrizeItem();
							firstItem.setName("一等奖");
							firstItem.setWinningCount(firstNumColumn.toPlainTextString().trim());
							firstItem.setPrizeAmount(firstAmountColumn.toPlainTextString().trim());
							TableColumn secondNumColumn = tableRow.getColumns()[7];
							TableColumn secondAmountColumn = tableRow.getColumns()[8];
							LotteryDrawPrizeItem secondItem = new LotteryDrawPrizeItem();
							secondItem.setName("二等奖");
							secondItem.setWinningCount(secondNumColumn.toPlainTextString().trim());
							secondItem.setPrizeAmount(secondAmountColumn.toPlainTextString().trim());
							TableColumn thirdNumColumn = tableRow.getColumns()[9];
							TableColumn thirdAmountColumn = tableRow.getColumns()[10];
							LotteryDrawPrizeItem thirdItem = new LotteryDrawPrizeItem();
							thirdItem.setName("三等奖");
							thirdItem.setWinningCount(thirdNumColumn.toPlainTextString().trim());
							thirdItem.setPrizeAmount(thirdAmountColumn.toPlainTextString().trim());
							resultDetail.add(firstItem);
							resultDetail.add(secondItem);
							resultDetail.add(thirdItem);
							lotteryDraw.setResultDetail(resultDetail);
							break;
						}
					}
					break;
				}
			}
		} catch (ParserException e) {
			logger.error("数据解析错误==" + e.getMessage(), e);
			return null;
		}
		return lotteryDraw;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
		return null;
	}

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}

}
